<template>
  <div class="app-container">
    <div class="center-parent">
      <el-button v-if="!isEmptyStr(urlList[0])" type="primary" @click="open = true" v-hasPermi="['pv:home_image:edit']" plain>更换图片</el-button>
      <el-empty class="center-child" v-if="isEmptyStr(urlList[0])" description="未查询到可使用题库">
        <el-button :loading="loading" type="primary" @click="getImage">刷新</el-button>
      </el-empty>
      <div v-else class="center-child image-name">
        <el-image :preview-src-list="urlList" :src="urlList[0]"></el-image>
      </div>
    </div>

    <el-dialog title="更换背景图片" center :visible.sync="open" width="1000">
      <el-upload class="upload-demo" ref="upload" action="#" :auto-upload="false" :on-change="updateChange" :show-file-list="false">
        <el-button slot="trigger" size="small" type="success" plain>选取文件</el-button>
        <el-button class="ml10" size="small" type="primary" @click="updateImage" plain :disabled="isEmptyStr(viewImage)">确认更换</el-button>
        <p label="1">仅允许导入<span class="text-red">png</span>、<span class="text-red">jpg、</span><span class="text-red">jpeg</span>格式文件</p>
      </el-upload>
      <el-image :src="viewImage">
        <div slot="error" class="image-slot">
          <i class="el-icon-picture-outline"></i>
        </div>
      </el-image>
    </el-dialog>

  </div>
</template>

<script>
import {get_image, update_image} from "@/api/pv/home_image";

export default {
  name: "Home_image",
  data() {
    return {
      loading: false,
      urlList: [''],
      open: false,
      viewImage: '',
      file: null,
    };
  },
  created() {
    this.getImage();
  },
  methods: {
    getImage(){
      this.loading = true;
      get_image().then( response =>{
        this.urlList[0] = response.data.url + '?v='+Math.random();
        this.loading = false;
      })
    },
    updateChange(file,fileList){
      if (fileList.length > 1 && fileList.status !== "fail") {
        fileList.splice(0, 1);
      }
      //获取后缀
      var suffix = file.name.replace(/.+\./, "").toLowerCase()
      if (suffix != 'jpg' && suffix != 'png' && suffix != 'jpeg'){
        this.$message.warning('文件格式错误：'+suffix);
        return false;
      }
      //展示图片
      this.viewImage = URL.createObjectURL(file.raw);
      this.file = file;
    },
    updateImage(){
      update_image(this.file).then(response=>{
        location.reload();
      })
    }
  }
};
</script>
<style>
.image-name{
  width: 70%;
  height: 70%;
}
.update-image-name{
  width: 70%;
  height: 70%;
}
</style>
